<template>
  <el-row>
    <el-col :span="5" style="border-right: 1px solid #dfe6ec">
      <div class="comp-tree" style="height: 100vh">
        <el-button class="comp-tr-top" type="primary" size="small" @click="handleAddTop" style="width: 100%"> 添加顶级节点 </el-button>
        <!-- tree -->
        <el-input placeholder="输入关键字进行过滤~" v-model="filterText"></el-input>
        <el-tree
          ref="SlotTree"
          :data="treeList"
          :props="defaultProps"
          :current-node-key="currentNodekey"
          :filter-node-method="filterNode"
          :highlight-current="true"
          :expand-on-click-node="false"
          :node-key="NODE_KEY"
          :default-expanded-keys="showKey"
          @node-click="handleNodeClick"
        >
          <div class="comp-tr-node" slot-scope="{ node, data }" style="width: 5rem">
            <i v-if="data.parentId === '0'" class="el-icon-folder"></i>
            <i v-else class="el-icon-collection-tag"></i>
            <span style="margin-left: 10px"></span>
            <!-- 编辑状态 -->
            <template v-if="node.isEdit">
              <el-input v-model="data.name" autofocus size="mini" :ref="'slotTreeInput' + data[NODE_KEY]" @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)"></el-input>
            </template>

            <!-- 非编辑状态 -->
            <template v-else>
              <!-- 名称： 新增节点增加class（is-new） -->
              <span :class="[data[NODE_KEY] < NODE_ID_START ? 'is-new' : '', 'comp-tr-node--name']">
                {{ node.label }}
              </span>
              <el-dropdown placement="top" style="margin-left: 10%">
                <span class="el-dropdown-link">
                  <i class="el-icon-more el-icon--right"></i>
                </span>
                <el-dropdown-menu>
                  <!-- 新增 -->
                  <el-tooltip class="item" effect="dark" content="添加子节点" placement="top">
                    <el-button
                      icon="el-icon-plus"
                      size="large"
                      circle
                      title="添加子节点"
                      @click="handleAdd(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="查看详情" placement="top">
                    <!-- 查看 -->
                    <el-button
                      icon="el-icon-document"
                      size="large"
                      circle
                      title="查看节点详情"
                      @click="handleLook(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="编辑节点" placement="top">
                    <el-button
                      icon="el-icon-edit"
                      size="large"
                      circle
                      title="编辑节点"
                      @click="handleEdit(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="删除节点" placement="top">
                    <el-button
                      icon="el-icon-delete"
                      size="large"
                      circle
                      title="删除节点"
                      @click="handleDeletetree(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                </el-dropdown-menu>
              </el-dropdown>
              <!--              <el-dropdown @command="handleButtonClick" trigger="click" placement="top-right" style="margin-left: 5%;">-->
              <!--                <i class="el-icon-more"></i>-->
              <!--                -->
              <!--              </el-dropdown>-->
            </template>
          </div>
        </el-tree>
        <treeData ref="treeForm" @getTreeList="getTreeList" />
      </div>
      <!--      <div class="comp-tree">-->
      <!--        <el-button class="comp-tr-top" type="primary" size="small" @click="handleAddTop">添加顶级节点</el-button>-->
      <!--        &lt;!&ndash; tree &ndash;&gt;-->
      <!--        <el-tree ref="SlotTree" :data="treeList" :props="defaultProps" :expand-on-click-node="false" :current-node-key="currentNodekey" :highlight-current="true"-->
      <!--          :node-key="NODE_KEY" @node-click="handleNodeClick">-->
      <!--          <div class="comp-tr-node" slot-scope="{ node, data }">-->
      <!--            &lt;!&ndash; 编辑状态 &ndash;&gt;-->
      <!--            <template v-if="node.isEdit">-->
      <!--              <el-input v-model="data.name" autofocus size="mini" :ref="'slotTreeInput' + data[NODE_KEY]"-->
      <!--                @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)"></el-input>-->
      <!--            </template>-->

      <!--            &lt;!&ndash; 非编辑状态 &ndash;&gt;-->
      <!--            <template v-else>-->
      <!--              &lt;!&ndash; 名称： 新增节点增加class（is-new） &ndash;&gt;-->
      <!--              <span :class="[data[NODE_KEY] < NODE_ID_START ? 'is-new' : '', 'comp-tr-node&#45;&#45;name']">-->
      <!--                {{ node.label }}-->
      <!--              </span>-->

      <!--              &lt;!&ndash; 按钮 &ndash;&gt;-->
      <!--              <span class="comp-tr-node&#45;&#45;btns">-->

      <!--                &lt;!&ndash; 新增 &ndash;&gt;-->
      <!--                <el-button icon="el-icon-plus" size="mini" circle type="primary" title="添加子节点"-->
      <!--                  @click="handleAdd(node, data)"></el-button>-->
      <!--                &lt;!&ndash; 查看 &ndash;&gt;-->
      <!--                <el-button icon="el-icon-document" size="mini" circle type="warning" title="查看节点详情"-->
      <!--                  @click="handleLook(node, data)"></el-button>-->
      <!--                &lt;!&ndash; 编辑 &ndash;&gt;-->
      <!--                <el-button icon="el-icon-edit" size="mini" circle type="info" title="编辑节点"-->
      <!--                  @click="handleEdit(node, data)"></el-button>-->

      <!--                &lt;!&ndash; 删除 &ndash;&gt;-->
      <!--                <el-button icon="el-icon-delete" size="mini" circle type="danger" title="删除节点"-->
      <!--                  @click="handleDeletetree(node, data)"></el-button>-->

      <!--              </span>-->
      <!--            </template>-->
      <!--          </div>-->
      <!--        </el-tree>-->
      <!--        <treeData ref="treeForm" @getTreeList="getTreeList" />-->
      <!--      </div>-->
    </el-col>
    <el-col :span="19">
      <div class="app-container">
        <div class="filter-container">
          <div class="filter-item">
            <span class="span">信息项名称:</span>
            <el-input v-model="listQuery.name" placeholder="请输入信息项名称" style="width: 200px" />
          </div>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>
          <el-button v-waves v-permission="['standardsystem:ModelSpecification:add']" class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleCreate">
            {{ $t('table.add') }}
          </el-button>
          <el-button v-waves class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-download" @click="handleDown"> 下载信息项 </el-button>
          <el-button v-waves v-permission="['standardsystem:ModelSpecification:delete']" class="filter-item" style="margin-left: 10px" type="danger" icon="el-icon-delete" @click="handleBathDelete">
            {{ $t('table.delete') }}
          </el-button>
          <!-- <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-upload" @click="handleImport">
            {{ $t('table.import') }}
          </el-button> -->
        </div>

        <el-table
          ref="table"
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="正在加载，请稍后"
          :data="list"
          border
          fit
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" width="50" label="序号" align="center" />
          <el-table-column label="信息项名称" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="英文名称" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.engName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="简称" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.shortName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数据类型" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.dataType | dictLabel('model_data_type') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="长度" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.dataSize }}</span>
            </template>
          </el-table-column>
          <el-table-column label="同义词" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.synonym }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <el-switch
                class="tableScopeSwitch"
                :width="width"
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                :inline-prompt="true"
                inactive-text="禁止"
                @change="changeType(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" min-width="230" class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <el-button v-permission="['standardsystem:ModelSpecification:update']" type="text" size="small" icon="el-icon-edit" @click="handleUpdate(row)">
                {{ $t('table.edit') }}
              </el-button>
              <el-button v-permission="['standardsystem:ModelSpecification:delete']" type="text" size="small" icon="el-icon-delete" class="delete-text-btn" @click="handleDelete(row)">
                {{ $t('table.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" />

        <model-specification-form ref="form" @refreshList="getList" />
        <importview ref="showimport" />
      </div>
    </el-col>
  </el-row>
</template>

<script>
// import { fetchMasterdataDirectoryList } from '@/api/masterdata/masterdataDirectory'
import { deleteModelSpecification, fetchModelSpecificationList, useAndStop, fileDown } from '@/api/standardsystem/modelSpecification'
import { fetchMasterdataDirectoryList, createMasterdataDirectory, updateMasterdataDirectory, getMasterdataDirectory, deleteMasterdataDirectory } from '@/api/masterdata/masterdataDirectory'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import treeData from './treeData.vue'
import modelSpecificationForm from './modelSpecificationForm'
import Pagination from '@/components/Pagination'
// 上传文件组件
import importview from '@/components/modelImport/index.vue'

export default {
  name: 'ModelSpecificationList',
  components: { modelSpecificationForm, Pagination, treeData, importview },
  directives: { waves, permission },
  data() {
    return {
      filterText: '',
      tableKey: 0,
      treeList: [],
      list: null,
      total: 0,
      multipleSelection: [],
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        name: undefined,
        ancestralId: '2',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      activeName: 'first', //tarbar
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 5, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      showKey: false,
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,
        children: [],
      },
      directoryId: '', //选中目录ID
      currentNodekey: '',
      value: '',
      true: true,
      width: 100,
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },
  created() {
    this.getTreeList()
    // this.getList()
  },
  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  methods: {
    handleImport() {
      this.$refs.showimport.show()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    changeType(row) {
      let obj = { id: row.id }
      let msg = ''
      if (row.status == 0) {
        obj.status = 0
        msg = '禁用'
      } else {
        obj.status = 1
        msg = '启用'
      }
      this.$confirm('确定要' + msg + '吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: msg + '成功!',
          })
          useAndStop(obj).then((response) => {
            if (response.data.code === 0) {
              this.$message.success(response.data.msg)
              this.$nextTick(() => {
                this.getList()
              })
            } else {
              this.$message.error(response.data.msg)
            }
          })
        })
        .catch(() => {
          console.log(row.status)
          row.status = row.status == 0 ? 1 : 0
          this.$message({
            type: 'info',
            message: '已取消' + msg,
          })
        })
    },
    handleAdd(_node, _data) {
      // 新增节点
      console.log(_node, _data)
      // // 判断层级
      if (_node.level >= this.MAX_LEVEL) {
        this.$message.warning('当前已达到' + this.MAX_LEVEL + '级，无法新增！')
        return false
      }
      // 参数修改
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = _data.id // 父id
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      this.$refs.treeForm.handleCreate(obj, 2)
      // 判断字段是否存在
      // if(!_data.children){
      // 	this.$set(_data, 'children', [])
      // }
      // 展开节点
      // if(!_node.expanded){
      // 	_node.expanded = true
      // }
    },
    handleDeletetree(_node, _data) {
      // 删除节点

      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              deleteMasterdataDirectory(_data.id).then((res) => {
                 
                this.$message.success('删除成功！')
                this.$refs.SlotTree.remove(_data)
              })
            }
          })
        }

        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此节点？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              DeletOprate()
            })
            .catch(() => {})
        }

        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START ? DeletOprate() : ConfirmFun()
      }
    },
    handleEdit(_node, _data) {
      // 编辑节点
      console.log(_node, _data)
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
      }
      this.$refs.treeForm.handleUpdate(obj, 2)
      // // 设置编辑状态
      // if(!_node.isEdit){
      // 	this.$set(_node, 'isEdit', true)
      // }

      // // 输入框聚焦
      // this.$nextTick(() => {
      // 	if(this.$refs['slotTreeInput'+_data[this.NODE_KEY]]){
      // 		this.$refs['slotTreeInput'+_data[this.NODE_KEY]].$refs.input.focus()
      // 	}
      // })
    },
    handleLook(_node, _data) {
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
      }
      this.$refs.treeForm.handleLook(obj, 2)
    },
    handleAddTop() {
      // 添加顶部节点
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = 0
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      // console.log(obj,'顶部参数')
      this.$refs.treeForm.handleCreate(obj, 2)
    },
    handleNodeClick(data) {
    
      this.listQuery.directoryId = data.id
      //  this.directoryId=data.id
      this.getList()
    },
    handleClick(val) {
       
    },
    getTreeList() {
      this.listLoading = true
      fetchMasterdataDirectoryList(this.listQuery).then((response) => {
        if (response.data.code === 200) {
          this.treeList = response.data.data
          if (this.treeList.length > 0) {
            this.listQuery.directoryId = this.treeList[0].children[0].id
            this.currentNodekey = this.treeList[0].id
            this.getList()
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
            })
          }
          this.listLoading = false
          // this.$refs.form.setList(this.treeList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    load(tree, treeNode, resolve) {
      resolve(tree.children)
    },
    getListByTreeId(data) {
      this.listQuery.directory_id = data.id
      this.getList()
    },
    getList() {
      this.listLoading = true
      fetchModelSpecificationList(this.listQuery).then((response) => {
        if (response.data.code == 200) {
          this.list = response.data.data.records
          this.total = response.data.data.total
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
          this.listLoading = false
        }
      })
    },
    handleCreate() {
      this.$refs.form.setList(this.treeList)
      this.$refs.form.handleCreate()
    },
    handleUpdate(row) {
      this.$refs.form.setList(this.treeList)
      this.$refs.form.handleUpdate(row.id)
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteModelSpecification({ id: row.id }).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleDown() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      // fileDown(arr).then(res => {
      //    
      // })

      this.$confirm('确定下载所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        fileDown({ ids: this.ids, responseType: 'arraybuffer' }).then((response) => {
          console.log(response)
          if (response.status == 200) {
            // import('@/vendor/Export2Excel').then(excel => {
            //   excel.export_byte_to_excel(response.data.data, '11')
            //   this.downloadLoading = false
            // })
            const objectUrl = URL.createObjectURL(
              new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
              })
            )
            const link = document.createElement('a')
            // 设置导出的文件名称
            link.download = `模型规范` + '.xlsx'
            link.style.display = 'none'
            link.href = objectUrl
            link.click()
            document.body.appendChild(link)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteModelSpecification({ id: row.id, delFlag: 1 }).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}
#treeBox {
  margin-top: 1px;

  .el-table thead {
    display: none;
  }
}

.tableScopeSwitch .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}

/*打开时文字位置设置*/
.tableScopeSwitch .el-switch__label--right {
  z-index: 1;
  right: 6px;
}

/*关闭时文字位置设置*/
.tableScopeSwitch .el-switch__label--left {
  z-index: 1;
  left: 6px;
}

/*显示文字*/
.tableScopeSwitch .el-switch__label.is-active {
  display: block;
}

.tableScopeSwitch.el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 60px !important;
  /*开关按钮的宽度大小*/
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
